<?php
/**
 * Issue Model Class File
 *
 * @package
 * @author Joachim Werner <joachim.werner@diggin-data.de>
 */

/**
 * This is the model class for table "issue".
 *
 * The followings are the available columns in table 'issue':
 * @property integer $id
 * @property integer $projectId
 * @property integer $ownerId
 * @property string $summary
 * @property string $issueType
 * @property string $issueStatus
 * @property integer $priority
 * @property string $milestone
 * @property string $tags
 *
 * @package
 * @author Joachim Werner <joachim.werner@diggin-data.de>
 * @version $Rev: 7 $
 */
class Issue extends MyModel
{
    // {{{ *** Members ***

    /**
     * List of fields composing the record name (separated by ;)
     * @var string
     */
    var $nameFields = "summary;id";

    /**
     * Name format string (e.g. '{1} (#{2})' 
     * @var string
     */
    var $nameFormat = "{1} (#{2})";
    
    /**
     * Does this model use record revisions?
     * @var bool
     */
    var $usesRevision   = false;

    /**
     * Revision number of current record
     * @var int
     */
    var $recordRevision;

    /**
     * Does this model use logging?
     * @var bool
     */
     var $usesLog        = false;

     Const PRIORITY_LOW = 3;
     Const PRIORITY_MEDIUM = 2;
     Const PRIORITY_HIGH = 1;

    // }}} 
    // {{{ *** Methods ***
    // {{{ model
    /**
     * Returns the static model of the specified AR class.
     * @return Issue the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    } // }}} 
    // {{{ tableName
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'issue';
    } // }}} 
    // {{{ behaviors
    public function behaviors()
    {
        return array(
            'Timestamp2Behavior' => array(
                'class' => 'application.components.behaviors.TimestampBehavior',
            ),
            'swBehavior'=>array(
                'class' => 'application.extensions.simpleWorkflow.SWActiveRecordBehavior',
                'statusAttribute'=>'issueStatus',
            ),
        );
    } // }}} 
    // {{{ rules
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('issueType, summary, description, issueStatus, priority', 'required'),
            array('projectId', 'required', 'on'=>'insert'),
            array('projectId, milestoneId, ownerId, priority', 'numerical', 'integerOnly'=>true),
            array('summary', 'length', 'max'=>255),
            array('issueType', 'length', 'max'=>20),
            array('issueStatus', 'length', 'max'=>50),
            array('isChargeable','boolean'),
            array('hoursSpent', 'numerical'),
            array('ownerId, tags', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, projectId, ownerId, summary, issueType, issueStatus, priority, milestoneId, tags, isChargeable, hoursSpent', 'safe', 'on'=>'search'),
        );
    } // }}} 
    // {{{ relations
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'project'=>array(self::BELONGS_TO,'Project','projectId'),
            'milestone'=>array(self::BELONGS_TO,'Milestone','milestoneId'),
            'owner'=>array(self::BELONGS_TO,'User','ownerId'),
            'createdBy'=>array(self::BELONGS_TO,'User','userIdCreated'),
            'updatedBy'=>array(self::BELONGS_TO,'User','userIdUpdated'),                       'comments' => array(self::HAS_MANY, 'IssueComment', 'issueId', 'condition'=>'comments.status='.Comment::STATUS_APPROVED, 'order'=>'comments.create_time DESC'),
            'commentCount' => array(self::STAT, 'IssueComment', 'issueId', 'condition'=>'status='.Comment::STATUS_APPROVED),
 
        );
    } // }}} 
    // {{{ attributeLabels
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('site','ID'),
            'projectId' => Yii::t('site','Project'),
            'ownerId' => Yii::t('site','Owner'),
            'summary' => Yii::t('site','Summary'),
            'description' => Yii::t('site','Description'),
            'issueType' => Yii::t('site','Issue Type'),
            'issueStatus' => Yii::t('site','Issue Status'),
            'priority' => Yii::t('site','Priority'),
            'milestoneId' => Yii::t('site','Milestone'),
            'tags' => Yii::t('site','Tags'),
            'isChargeable' => Yii::t('site','Chargeable'),
            'hoursSpent' => Yii::t('site','Hours Spent'),
            'tsCreated' => Yii::t('site','Created'),
            'userIdCreated' => Yii::t('site','Created By'),
            'tsUpdated' => Yii::t('site','Updated'),
            'userIdUpdated' => Yii::t('site','Updated By'),
            'tsCreated' => Yii::t('site','Created'),
            'userIdCreated' => Yii::t('site','Created By'),
            'tsUpdated' => Yii::t('site','Updated'),
            'userIdUpdated' => Yii::t('site','Updated By'),
        );
    } // }}} 
    // {{{ search
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        if(!is_null(Yii::app()->user->getState('SelectedProjectId'))) {
            $criteria->addCondition('projectId='.Yii::app()->user->getState('SelectedProjectId'));
        } else {
            $criteria->compare('projectId',$this->projectId);
        }
        if(!is_null(Yii::app()->user->getState('SelectedMilestoneId'))) {
            $criteria->addCondition('milestoneId='.Yii::app()->user->getState('SelectedMilestoneId'));
        } else {
            $criteria->compare('milestoneId',$this->milestoneId);
        }
        $criteria->compare('ownerId',$this->ownerId);
        $criteria->compare('summary',$this->summary,true);
        $criteria->compare('description',$this->description);
        $criteria->compare('issueType',$this->issueType,true);
        $criteria->compare('issueStatus',$this->issueStatus,true);
        $criteria->compare('priority',$this->priority);
        //$criteria->compare('milestoneId',$this->milestoneId,true);
        $criteria->compare('tags',$this->tags,true);
        $criteria->compare('isChargeable',$this->isChargeable);
        $criteria->compare('hoursSpent',$this->hoursSpent, true);
        return new CActiveDataProvider(get_class($this), array('criteria'=>$criteria,'sort'=>array('defaultOrder'=>'priority')));
    } // }}} 
    // {{{ crosstab
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function crosstab($row = null, $column = null, $cell = 'COUNT(t.id)')
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        if(!is_null(Yii::app()->user->getState('SelectedProjectId'))) {
            $criteria->addCondition('t.projectId='.Yii::app()->user->getState('SelectedProjectId'));
        } else {
            $criteria->compare('t.projectId',$this->projectId);
        }
        $criteria->compare('ownerId',$this->ownerId);
        $criteria->compare('summary',$this->summary,true);
        $criteria->compare('issueType',$this->issueType,true);
        $criteria->compare('issueStatus',$this->issueStatus,true);
        $criteria->compare('priority',$this->priority);
        $criteria->compare('milestoneId',$this->milestoneId,true);
        $criteria->compare('tags',$this->tags,true);
        $criteria->select = 'm.name, t.priority, COUNT(t.id)';
        $criteria->group = 'm.name, t.priority';
        $criteria->join = "RIGHT JOIN Milestone m ON t.milestoneId=m.id";
        //$criteria->with = array('milestone');
        echo par($criteria->toArray());
        foreach(Issue::model()->findAll($criteria) as $row)
            echo par($row->attributes);
die;
        return new CActiveDataProvider(Issue::model()->with('milestone'), /* get_class($this), */ array('criteria'=>$criteria,'sort'=>array('defaultOrder'=>'milestone.name,t.priority')));
    } // }}} 
    // {{{ getPriorityOptions
    public function getPriorityOptions()
    {
        return array(
            self::PRIORITY_LOW      => Yii::t('site','Low'),
            self::PRIORITY_MEDIUM   => Yii::t('site','Medium'),
            self::PRIORITY_HIGH     => Yii::t('site','High'),
        );
    } // }}} 
    // {{{ getPriorityValuesByNames
    public function getPriorityValuesByNames()
    {
        $result = array();
        $options = $this->priorityOptions;
        foreach($options as $key=>$value)
            $result[$key.' - '.$value] = $key;
        return $result;
    } // }}} 
    // {{{ getIssueTypeOptions
    public function getIssueTypeOptions()
    {
        return array(
            'Bug'               => Yii::t('site','Bug'),
            'Enhancement'       => Yii::t('site','Enhancement'),
            'Feature Request'   => Yii::t('site','Feature Request'),
            'Task'              => Yii::t('site','Task'),
            'Other'             => Yii::t('site','Other'),
        );
    } // }}} 
    // {{{ addComment
    /**
     * Adds a new comment to this issue.
     * This method will set status and issueId of the comment accordingly.
     * @param Comment the comment to be added
     * @return boolean whether the comment is saved successfully
     */
    public function addComment($comment)
    {
        if(Yii::app()->params['issueCommentsNeedApproval'])
            $comment->status=Comment::STATUS_PENDING;
        else
            $comment->status=Comment::STATUS_APPROVED;
        $comment->issueId=$this->id;
        return $comment->save();
    } // }}} 
    // {{{ afterDelete
    /**
     * This is invoked after the record is deleted.
     */
    protected function afterDelete()
    {
        parent::afterDelete();
        IssueComment::model()->deleteAll('issueId='.$this->id);
    } // }}}
    // {{{ getUrl
    /**
     * @return string the URL that shows the detail of the post
     */
    public function getUrl()
    {
        return Yii::app()->createUrl('/issue/view', array(
            'id'=>$this->id,
            'title'=>$this->summary,
        ));
    } // }}} 
    // }}} End Methods
}

/* vim: set ai sw=4 sts=4 et fdm=marker fdc=4 */ 
?>
